package pure.engine.monitor 
{
	import flash.events.MouseEvent;
	import pure.engine.entity.Fragment;
	import pure.engine.world.WorldBody;
    import pure.engine.core.ns_despair;
    
    use namespace ns_despair;

	/**
	 * ...
	 * @author Pure
	 */
public class MonitorForMouse extends MonitorCore
{
	public function MonitorForMouse(width:Number, height:Number, worldBody:WorldBody, duration:Number, color:uint)
	{
		super(width, height, worldBody, duration, color);
	}
	
	
	
	

	protected var _mouseRegistered:Boolean;    // 是否已注册滑鼠侦听

	
	
	// 毁灭
	override public function destroy():void
	{
		super.destroy();
		
		this.mouseEnabled  =  false;
	}



	 
	// 是否侦听滑鼠
	override public function set mouseEnabled(b:Boolean):void
	{
		if (this.mouseEnabled == b)  return;
		
		super.mouseEnabled = b;
		if (b)
		{
			if (!_mouseRegistered && !_waiting)
			{
				this.addEventListener( MouseEvent.MOUSE_DOWN, ____onMouseInteract );
				this.addEventListener( MouseEvent.MOUSE_UP,   ____onMouseInteract );
				this.addEventListener( MouseEvent.MOUSE_MOVE, ____onMouseInteract );
				_mouseRegistered = true;
			}
		}
		else
		{
			if (_mouseRegistered)
			{
				this.removeEventListener(MouseEvent.MOUSE_DOWN, ____onMouseInteract);
				this.removeEventListener(MouseEvent.MOUSE_UP,   ____onMouseInteract);
				this.removeEventListener(MouseEvent.MOUSE_MOVE, ____onMouseInteract);
				_mouseRegistered = false;
			}
		}
	}

	
	// 滑鼠世界位置
	public function get mouseWorldX():Number { return this.mouseX + m_x; }
	public function get mouseWorldY():Number { return this.mouseY + m_y; }
	
	
	

	/* ----------------------------------------------------------------------------------------------------------------
	 * ★★★★★★★★★★★★★★★★★★★★★  private  ★★★★★★★★★★★★★★★★★★★★★
	 * ----------------------------------------------------------------------------------------------------------------
	 */
	
	 
	
	// [Event]
	// 滑鼠交互侦听
	protected function ____onMouseInteract(e:MouseEvent):void
	{
		if (!m_worldBody)  return;
		
		e.updateAfterEvent();
		
		var fragments:Array
		var F:Fragment;
		var len:int;
		
		cachedPoint.x  =  e.stageX;
		cachedPoint.y  =  e.stageY;
		fragments      =  this.getObjectsUnderPoint(cachedPoint);
		len            =  fragments.length;
		
		while(--len > -1)
		{
			if (!(fragments[len] is Fragment))  continue;
			
			F  =  fragments[len];
			if (F.interactive)
			{
				if (F.bitmapData.getPixel32((F.mouseX + 0.5 >> 0), (F.mouseY + 0.5 >> 0)) > 0)
				{
					m_worldBody.updateMouseState( e.type, F, this.mouseX + m_x, this.mouseY + m_y, cachedPoint.x, cachedPoint.y);
					return;
				}
			}
		}
		m_worldBody.updateMouseState(e.type, null, this.mouseX + m_x, this.mouseY + m_y, cachedPoint.x, cachedPoint.y);
	}
	
	
}

}